//
//  ICENavigatorProcesser.m
//  ICEubLib
//
//  Created by wujianrong on 16/4/12.
//  Copyright © 2016年 wanda. All rights reserved.
//

#import "ICENavigatorQueue.h"
#import "ICENavigatorAction.h"
#import "ICECore.h"

@interface ICENavigatorQueue()
{
    NSMutableArray* _urlStringArray;
}
@end

static ICENavigatorQueue* _ICEQueueSharedInstance = nil;

@implementation ICENavigatorQueue

+(instancetype)defaultManager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _ICEQueueSharedInstance = [[ICENavigatorQueue alloc] init];
    });
    
    return _ICEQueueSharedInstance;
}

-(instancetype)init
{
    self = [super init];
    if (self) {
        _urlStringArray = [[NSMutableArray alloc]init];
    }
    return self;
}

-(void)addASchemeWithUrl:(id)url fromViewController:(UIViewController *)controller initAfterAlloc:(iceNavigatorInitAfterViewControllerAlloc)block
{
    NSString* relyingUrl = [ICENavigatorAction checkRelyingOnViewControllerWithUrl:url];
    if (ICESafeString(relyingUrl).length <= 0) {
        [ICENavigatorAction openURLString:url fromViewController:controller initAfterAlloc:block];
        return;
    }
    
    if (ICESafeString(url).length > 6) {
        [_urlStringArray addObject:[url copy]];
        [self addASchemeWithUrl:relyingUrl fromViewController:nil];
    }
}

-(void)addASchemeWithUrl:(id)url fromViewController:(UIViewController *)controller
{
    if ([ICENavigatorAction isCurrentVcTopLevelWithFromViewController:controller url:url] == YES) {
        if (ICESafeString(url).length > 6) {
            [_urlStringArray addObject:[url copy]];
        }
        return;
    }
    
    NSString* relyingUrl = [ICENavigatorAction checkRelyingOnViewControllerWithUrl:url];
    if (ICESafeString(relyingUrl).length <= 0) {
        [ICENavigatorAction openURLString:url fromViewController:controller];
        return;
    }
    
    if (ICESafeString(url).length > 6) {
        [_urlStringArray addObject:[url copy]];
        [self addASchemeWithUrl:relyingUrl fromViewController:nil];
    }
}

-(void)notifyQueue
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        @synchronized(self){
            if (_urlStringArray.count > 0) {
                NSString* lastUrl = [_urlStringArray lastObject];
                [_urlStringArray removeLastObject];
                [ICENavigatorAction openURLString:lastUrl fromViewController:nil];
            }
        }
    });
}

-(void)queuePopAllUrlscheme
{
    if (_urlStringArray.count > 0) {
        [_urlStringArray removeAllObjects];
    }
}

-(NSArray*)checkRelyingViewContllerQueueWithUrl:(NSString*)url
{
    
    return nil;
}
@end
